package com.crois.barrier.admin.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crois.barrier.admin.entity.*;
import com.crois.barrier.admin.enums.PositionTypeEnum;
import com.crois.barrier.admin.mapper.*;
import com.crois.barrier.common.exception.BarrierException;
import com.crois.barrier.common.exception.BarrierExceptionEnum;
import com.zhimydou.ztools.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;

/**
 * barrier api路由信息
 * @author Hou Ze Yu
 * @date 2021-10-25 11:58:25
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ApiRouteInfoSvc extends ServiceImpl<ApiRouteInfoMapper,ApiRouteInfo> implements IApiRouteInfoSvc {

    @Autowired
    private ApiParameterInfoMapper apiParameterInfoMapper;

    @Autowired
    private ApiResponseInfoMapper apiResponseInfoMapper;

    @Autowired
    private ApiFailCodeInfoMapper apiFailCodeInfoMapper;


    @Autowired
    @Qualifier("nacosConfigSvc")
    private INaocsConfigSvc naocsConfigSvc;






    @Override
    public List<ApiRouteInfo> findApiRouteList(String apiRouteName, Integer apiGroupId) {

        QueryWrapper<ApiRouteInfo> apiRouteInfoQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(apiRouteName)) {

            apiRouteInfoQueryWrapper.lambda().like(ApiRouteInfo::getApiRouteName,"%"+apiRouteName+"%");

        }

        if (!Objects.isNull(apiGroupId)) {
            apiRouteInfoQueryWrapper.lambda().eq(ApiRouteInfo::getApiRouteGroupId,apiGroupId);
        }
        return baseMapper.selectList(apiRouteInfoQueryWrapper);

    }

    @Override
    public void updateRoutePush(ApiRouteInfo newApiRouteInfo) {
        int result = baseMapper.updateById(newApiRouteInfo);
        if (result==0){
          throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_SYNC_FAIL);
        }
        naocsConfigSvc.pushApiRoute();
    }

    @Override
    public void saveRoute(ApiRouteInfo apiRouteInfo) {
        int result = baseMapper.insert(apiRouteInfo);
        if (result==0) {
            log.error("【barrier】，route_id:{}，添加route失败!",apiRouteInfo.getId());
            throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_ADD_FAIL);
        }
        List<ApiParameterInfo> apiParameter = apiRouteInfo.getApiParameter();
        if (!Objects.isNull(apiParameter)){
            for (ApiParameterInfo apiParameterInfo : apiParameter) {
                apiParameterInfo.setApiRouteId(apiRouteInfo.getId());
                apiParameterInfo.setPositionType(PositionTypeEnum.API_PARAMETER.getType());
                result = apiParameterInfoMapper.insert(apiParameterInfo);
                if (result==0) {
                    log.error("【barrier】，apiParameter_id:{}，添加apiParameter失败!",apiParameterInfo.getId());
                    throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_ADD_FAIL);
                }
            }
        }
        List<ApiParameterInfo> constantsParameter = apiRouteInfo.getConstantsParameter();
        if (!Objects.isNull(constantsParameter)){
            for (ApiParameterInfo constantsParameterInfo : constantsParameter) {
                constantsParameterInfo.setApiRouteId(apiRouteInfo.getId());
                constantsParameterInfo.setPositionType(PositionTypeEnum.CONSTANTS.getType());
                result = apiParameterInfoMapper.insert(constantsParameterInfo);
                if (result==0) {
                    log.error("【barrier】，constantsParameter_id:{}，添加constantsParameter失败!",constantsParameterInfo.getId());
                    throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_ADD_FAIL);
                }
            }
        }
        ApiResponseInfo apiResponse = apiRouteInfo.getApiResponse();

        if (!Objects.isNull(apiResponse)) {
            apiResponse.setApiRouteId(apiRouteInfo.getId());
            result = apiResponseInfoMapper.insert(apiResponse);
            if (result == 0) {
                log.error("【barrier】，apiResponse_id:{}，添加apiResponse失败!", apiResponse.getId());
                throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_ADD_FAIL);
            }

            // 添加响应码信息
            List<ApiFailCodeInfo> apiFailCodeInfoList = apiResponse.getApiFailCodeInfoList();
            if (!Objects.isNull(apiFailCodeInfoList)) {
                for (ApiFailCodeInfo apiFailCodeInfo : apiFailCodeInfoList) {
                    apiFailCodeInfo.setApiResponseId(apiResponse.getId());
                    result = apiFailCodeInfoMapper.insert(apiFailCodeInfo);
                    if (result == 0) {
                        log.error("【barrier】，apiFailCodeInfo_id:{}，添加ApiFailCodeInfo失败!", apiFailCodeInfo.getId());
                        throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_ADD_FAIL);
                    }
                }
            }
        }
        naocsConfigSvc.pushApiRoute();
    }

    @Override
    public void updateRoute(ApiRouteInfo apiRouteInfo) {
        // 更新 route
        int result = baseMapper.updateById(apiRouteInfo);
        if (result==0) {
            log.error("【barrier】，route_id:{}，修改route失败!",apiRouteInfo.getId());
            throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
        }
        // 删除参数
        QueryWrapper<ApiParameterInfo> apiParameterInfoQueryQueryWrapper = new QueryWrapper<>();
        apiParameterInfoQueryQueryWrapper.lambda().eq(ApiParameterInfo::getApiRouteId,apiRouteInfo.getId());
        List<ApiParameterInfo> oldApiParameterInfoList = apiParameterInfoMapper.selectList(apiParameterInfoQueryQueryWrapper);
        if (CollectionUtil.isNotEmpty(oldApiParameterInfoList)){
            result = apiParameterInfoMapper.deleteApiParameterInfo(apiRouteInfo.getId());
            if (result==0) {
                log.error("【barrier】，route_id:{}，删除parameter失败!",apiRouteInfo.getId());
                throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
            }
        }
        // 删除响应信息
         QueryWrapper<ApiResponseInfo> apiResponseInfoQueryWrapper = new QueryWrapper<>();
         apiResponseInfoQueryWrapper.lambda().eq(ApiResponseInfo::getApiRouteId,apiRouteInfo.getId());
         ApiResponseInfo oldApiResponseInfo = apiResponseInfoMapper.selectOne(apiResponseInfoQueryWrapper);
        if ( !Objects.isNull(oldApiResponseInfo) ) {
            Integer oldApiResponseInfoId = oldApiResponseInfo.getId();
             result = apiResponseInfoMapper.deleteApiResponseInfo(apiRouteInfo.getId());
             if (result==0) {
                 log.error("【barrier】，route_id:{}，删除responseInfo失败!",apiRouteInfo.getId());
                 throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
             }
             // 删除 错误码
             QueryWrapper<ApiFailCodeInfo> apiFailCodeInfoQueryWrapper = new QueryWrapper<>();
             apiFailCodeInfoQueryWrapper.lambda().eq(ApiFailCodeInfo::getApiResponseId,oldApiResponseInfoId);
             List<ApiFailCodeInfo> apiFailCodeInfoList = apiFailCodeInfoMapper.selectList(apiFailCodeInfoQueryWrapper);
             if (CollectionUtil.isNotEmpty(apiFailCodeInfoList)) {
                 result = apiFailCodeInfoMapper.deleteApiFailCodeInfo(oldApiResponseInfoId);
                 if (result==0) {
                     log.error("【barrier】，response_id:{}，删除failCodeInfo失败!",oldApiResponseInfo.getId());
                     throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
                 }
             }
         }
        // 重新 添加
        List<ApiParameterInfo> apiParameter = apiRouteInfo.getApiParameter();
         if (!Objects.isNull(apiParameter)){
             for (ApiParameterInfo apiParameterInfo : apiParameter) {
                 apiParameterInfo.setApiRouteId(apiRouteInfo.getId());
                 apiParameterInfo.setPositionType(PositionTypeEnum.API_PARAMETER.getType());
                 result = apiParameterInfoMapper.insert(apiParameterInfo);
                 if (result==0) {
                     log.error("【barrier】，apiParameter_id:{}，添加apiParameter失败!",apiParameterInfo.getId());
                     throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
                 }
             }
         }
        List<ApiParameterInfo> constantsParameter = apiRouteInfo.getConstantsParameter();
        if (!Objects.isNull(constantsParameter)){
            for (ApiParameterInfo constantsParameterInfo : constantsParameter) {
                constantsParameterInfo.setApiRouteId(apiRouteInfo.getId());
                constantsParameterInfo.setPositionType(PositionTypeEnum.CONSTANTS.getType());
                result = apiParameterInfoMapper.insert(constantsParameterInfo);
                if (result==0) {
                    log.error("【barrier】，constantsParameter_id:{}，添加constantsParameter失败!",constantsParameterInfo.getId());
                    throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
                }
            }
        }
        ApiResponseInfo apiResponse = apiRouteInfo.getApiResponse();

        if (!Objects.isNull(apiResponse)){
            apiResponse.setApiRouteId(apiRouteInfo.getId());
            result = apiResponseInfoMapper.insert(apiResponse);
            if (result==0) {
                log.error("【barrier】，apiResponse_id:{}，添加apiResponse失败!",apiResponse.getId());
                throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
            }

            // 添加响应码信息
            List<ApiFailCodeInfo> apiFailCodeInfoList = apiResponse.getApiFailCodeInfoList();
            if (!Objects.isNull(apiFailCodeInfoList)){
                for (ApiFailCodeInfo apiFailCodeInfo : apiFailCodeInfoList) {
                    apiFailCodeInfo.setApiResponseId(apiResponse.getId());
                    result = apiFailCodeInfoMapper.insert(apiFailCodeInfo);
                    if (result==0) {
                        log.error("【barrier】，apiFailCodeInfo_id:{}，添加ApiFailCodeInfo失败!",apiFailCodeInfo.getId());
                        throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_ROUTE_UPDATE_FAIL);
                    }
                }
            }
        }
        naocsConfigSvc.pushApiRoute();
    }


}
